<?php

/**
 * Created by PhpStorm.
 * User: nirui
 * Date: 17-6-29
 * Time: 上午11:02
 */
class purchaseorderdetails{

    //报表列名
    static $title=array(
        'purchaseordersid'=>'采购单号',
        'purchasetime'=>'采购时间',
        'enterprise_dominant'=>'主体',
        'export_tax_rebate'=>'退税类型',
        'warehouseid'=>'仓库类型',
        'store'=>'目的仓',
        'payway'=>'付款方式',
        'purchaser'=>'采购员',
        'supplier'=>'供应商',
        'transfer_hopper_id'=>'转运仓库',
        'transfer_type'=>'转运方式',
        'remark'=>'备注',
        'sku'=>'SKU',
        'skucname'=>'SKU中文名',
        'specimen'=>'是否样品下单',
        'unit'=>'单位',
        'item'=>'品名',
        'singleprice'=>'单价（包含加点税计算）',
        'purchasequantity'=>'采购数量',
        'recievequantity'=>'收货数量',
        'checkquantity'=>'质检数量',
        'warehousequantity'=>'入库数量',
        'unqualityquantity'=>'不良品数量'
    );

    //20万一次写入
    static $downloadLimitNumber=200000;

    //最大一次下载数量为1千万
    static $maxDownloadNumber=10000000;

    /**
     * @param $condition 筛选条件
     * @return mixed 返回符合筛选条件的记录数量
     * 计数方法，统计符合筛选条件的记录条数
     */
    public static function countData($condition){
        $conditonsql=self::getConditionsql($condition);
        $datas=DB::query(
            Database::SELECT,
            'SELECT COUNT(1) `countN`
FROM `purchaseorders` p
LEFT JOIN `purchaseorder_details` pd
ON pd.`purchaseorder_id`=p.`id`
WHERE 1 '.$conditonsql
        )
            ->execute('newerp')
            ->get('countN');
        return $datas;
    }

    /**
     * @param $condition 筛选条件
     * @param $limitsql 分页sql
     * @return mixed 返回符合条件的记录详情（筛选条件包含分页条件）
     * 获取符合筛选条件的记录详情
     */
    public static function getData($condition,$limitsql=''){
        $conditonsql=self::getConditionsql($condition);
        $datas=DB::query(
            Database::SELECT,
            'SELECT p.`id` `purchaseordersid`, p.`warehouseid` `warehouseid`, p.`purchaseorder_date` `purchasetime`, p.`supplier_id` `supplier`,
p.`pay_way` `payway`, p.`purchase_id` `purchaser`,p.`status`, p.`store` `store`, p.`export_tax_rebate` `export_tax_rebate`,
p.`enterprise_dominant` `enterprise_dominant`, p.`transfer_hopper_id` `transfer_hopper_id`, p.`transfer_type` `transfer_type`,
p.`specimen` `specimen`,p.`remark` `remark`,
pd.`sku` `sku`, pd.`sku_name` `skucname`, pd.`quantity` `purchasequantity`, pd.`single_price`*(1+pd.`real_tax_rate`) `singleprice`,
pd.`recieve_quantity` `recievequantity`, pd.`check_quantity` `checkquantity`, pd.`return_quantity` `unqualityquantity`,
pd.`ware_quantity` `warehousequantity`, pd.`item` `item`, pd.`sku_unit` `unit`
FROM `purchaseorders` p
LEFT JOIN `purchaseorder_details` pd
ON pd.`purchaseorder_id`=p.`id`
WHERE 1 '.$conditonsql.$limitsql
        )
            ->execute('newerp')
            ->as_array();
        return $datas;
    }

    /**
     * @param $datas 需要进行转义的信息
     * @return mixed 转义后的信息
     */
    public static function transform($datas){
        if(in_array('enterprise_dominant',array_keys($datas[0]))){
            $transforms['enterprise_dominant']=disaster::getEnterprise_dominantsByIds();
        }
        if(in_array('export_tax_rebate',array_keys($datas[0]))){
            $transforms['export_tax_rebate']=disaster::getExport_tax_rebatesByIds();
        }
        if(in_array('warehouseid',array_keys($datas[0]))){
            $transforms['warehouseid']=disaster::getWarehousesByIds();
        }
        if(in_array('store',array_keys($datas[0]))){
            $transforms['store']=disaster::getAllStores();
        }
        if(in_array('payway',array_keys($datas[0]))){
            $transforms['payway']=disaster::getAllPayways();
        }
        if(in_array('purchaser',array_keys($datas[0]))){
            $transforms['purchaser']=disaster::getAllPurchasers();
        }
        if(in_array('supplier',array_keys($datas[0]))){
            $transforms['supplier']=disaster::getAllSuppliers();
        }
        if(in_array('transfer_hopper_id',array_keys($datas[0]))){
            $transforms['transfer_hopper_id']=disaster::getTransfer_hoppersByIds();
        }
        if(in_array('transfer_type',array_keys($datas[0]))){
            $transforms['transfer_type']=disaster::getTransfer_typesByIds();
        }
        if(in_array('specimen',array_keys($datas[0]))){
            $transforms['specimen']=array(0=>'否',1=>'是',2=>'是');
        }
        foreach($datas as &$data){
            foreach(array_keys($transforms) as $key){
                $data[$key]=isset($transforms[$key][$data[$key]])?$transforms[$key][$data[$key]]:'';
            }
        }
        return $datas;
    }

    /**
     * @param $condition 查询条件
     * @return string 返回查询条件sql
     */
    public static function getConditionsql($condition){
        $conditionsql='';
        if(isset($condition['purchaseorderid'])&&!empty($condition['purchaseorderid'])){
            $conditionsql.=' AND p.`id`='.$condition['purchaseorderid'];
        }
        if(isset($condition['purchase_date_s'])&&!empty($condition['purchase_date_s'])){
            $conditionsql.=' AND p.`purchaseorder_date`>="'.$condition['purchase_date_s'].'"';
        }
        if(isset($condition['purchase_date_e'])&&!empty($condition['purchase_date_e'])){
            $conditionsql.=' AND p.`purchaseorder_date`<"'.$condition['purchase_date_e'].'"';
        }
        if(isset($condition['enterprise_dominants'])&&!empty($condition['enterprise_dominants'])){
            $conditionsql.=' AND p.`enterprise_dominant`='.$condition['enterprise_dominants'];
        }
        if(isset($condition['warehouseid'])&&!empty($condition['warehouseid'])){
            $conditionsql.=' AND p.`warehouseid`='.$condition['warehouseid'];
        }
        if(isset($condition['paywayid'])&&!empty($condition['paywayid'])){
            $conditionsql.=' AND p.`pay_way`='.$condition['paywayid'];
        }
        if(isset($condition['purchaseorderstatus'])&&!empty($condition['purchaseorderstatus'])){
            $conditionsql.=' AND p.`status`='.$condition['purchaseorderstatus'];
        }
        if(isset($condition['export_tax_rebate'])&&$condition['export_tax_rebate']!=''){
            $conditionsql.=' AND p.`export_tax_rebate`='.$condition['export_tax_rebate'];
        }
        if(isset($condition['supplier'])&&!empty($condition['supplier'])){
            $conditionsql.=' AND p.`supplier_id`='.$condition['supplier'];
        }
        if(isset($condition['purchaser'])&&!empty($condition['purchaser'])){
            $conditionsql.=' AND p.`purchase_id`='.$condition['purchaser'];
        }
        if(isset($condition['sku'])&&!empty($condition['sku'])){
            $conditionsql.=' AND pd.`sku`="'.$condition['sku'].'"';
        }
        return $conditionsql;
    }

    /**自动生成下载文件
     * @param $orders 字段顺序
     * @param $filename 文件名称
     * @param $head 列名
     * @param $infos 数据
     * @param $continue 续写标志位
     * @return mixed
     */
    static function download($orders,$filename,$head,$infos,$continue=0){
        // 处理头部标题
        $title='';
        foreach($orders as $order){
            $title.=empty($title)?$head[$order]:','.$head[$order];
        }
        $title.=PHP_EOL;
        // 处理内容
        $content = '';
        foreach ($infos as $info) {
            $singlecontent='';
            foreach($orders as $order){
                $singlecontent.=empty($singlecontent)?str_replace(array(',','\n','\r',';'), '',$info[$order])
                    :','.str_replace(array(',','\n','\r',';'), '',$info[$order]);
            }
            $singlecontent.=PHP_EOL;
            $content.= $singlecontent;
        }

        //文件是否存在，存在判断是否续写，不存在直接写入
        if(file_exists($filename)){
            //判断是否续写，续写不删除文件继续写入，不续写删除文件，重新写入
            if($continue=0){
                unlink ($filename);
                $csv = $title.$content;
            }else{
                $csv = $content;
            }
        }else{
            $csv = $title.$content;
        }
        // 写入并关闭资源
        $fp = fopen($filename,'a');
        fwrite($fp, $csv);
        fclose($fp);
        return $filename;
    }

    /**根据查询条件生成文件名称
     * @param $condition
     */
    static function getFilename(){
        $filename='采购明细报表';
        return $filename;
    }

}